package com.easpeed.comon.utils

import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.io.FileOutputStream

object SimpleFileDownloader {


    private val client = OkHttpClient()

    fun downloadFile(
        fileUrl: String,
        destination: File,
        progressListener: ((progress: Int, msg: String, success: Boolean) -> Unit)? = null,

        ): okhttp3.Call {
        val request = Request.Builder().url(fileUrl).build()
        val call = client.newCall(request)
        Thread {
            try {
                com.bigyu.utils.Logger.e("TAG", "downloadFile: start download")
                val response = call.execute()
                if (response.isSuccessful && response.body != null) {
                    val body = response.body!!
                    val contentLength = body.contentLength()
                    val inputStream = body.byteStream()
                    val outputStream = FileOutputStream(destination)

                    val buffer = ByteArray(2048)
                    var downloadedBytes = 0L
                    var bytesRead: Int

                    while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                        if (call.isCanceled()) {
                            println("Download canceled!")
                            destination.delete() // 删除未完成的文件
                            break
                        }

                        outputStream.write(buffer, 0, bytesRead)
                        downloadedBytes += bytesRead

                        com.bigyu.utils.Logger.e("TAG", "downloadFile: $downloadedBytes  $contentLength")
                        // 计算进度并回调
                        progressListener?.invoke(((downloadedBytes * 100) / contentLength).toInt(), "", true)
                    }

                    outputStream.flush()
                    if (!call.isCanceled()) {
                        println("Download complete!")
                    }
                } else {
                    progressListener?.invoke(0, "下载失败: ${response.message}", false)
                    com.bigyu.utils.Logger.e("TAG", "downloadFile: response is not successful")
                    println("Download failed: ${response.message}")
                }
            } catch (e: Exception) {
                com.bigyu.utils.Logger.e("TAG", "downloadFile: $e")
                if (call.isCanceled()) {
                    println("Download canceled due to user action.")
                } else {
                    e.printStackTrace()
                }
                progressListener?.invoke(0, "下载失败: ${e.message}", false)
            }
        }.start()
        return call
    }
}
